{ "cells": [ { "cell_type": "markdown", "id": "0", "metadata": {}, "source": [ "# Example: Machine symmetrisation\n", "\n", "---\n", "\n", "This notebook demonstrates how to turn an **approximately** up-down symmetric machine description into an **exact** up-down symmetric model. \n", "\n", "By building perfectly up-down symmetric machine descriptions, we can use the static/evolutive solvers (and virtual PCS) to evolve the plasma dynamics with much larger timesteps than is usually possible. This is because the vertical instability timescale typically limits the timestep sizes (recall the Example 05 notebooks). Of course this only works for up-down symmetric plasmas but can be a good approximation for plasma scenario design before adding the vertical instabilities back in. \n", "\n", "### Overview \n", "\n", "\n", "Let $Z_0$ be the symmetry midplane vertical coordinate, and define the vertical reflection operator $\\mathcal{R}_Z : (R, Z) \\mapsto (R, 2Z_0 - Z)$. Given an upper conductor element with coordinates $\\mathbf{x}_u = (R_u, Z_u)$ and its lower partner with coordinates $\\mathbf{x}_l = (R_l, Z_l)$, the paired geometry is replaced by its reflected average $\\mathbf{x}_{\\mathrm{sym}}$:\n", "\n", "$$\n", "\\mathbf{x}_{\\mathrm{sym}} = \\frac{1}{2}\\left(\\mathbf{x}_u + \\mathcal{R}_Z \\mathbf{x}_l\\right).\n", "$$\n", "\n", "Similarly, the currents $I_u$ (upper) and $I_l$ (lower) in an independently driven pair decompose into even ($I_+$) and odd ($I_-$) components:\n", "\n", "$$\n", "I_+ = \\frac{I_u + I_l}{2}, \\qquad I_- = \\frac{I_u - I_l}{2}.\n", "$$\n", "\n", "Only the even component $I_+$ is retained in the strictly symmetric machine, while the original currents remain recoverable via $I_u = I_+ + I_-$ and $I_l = I_+ - I_-$.\n", "\n", "Below, we:\n", "1. Build an imperfect toy machine (similar to the Anamak in Example 07a) with a small vertical offset, centimetre-scale upper/lower mismatches, and one electrically odd vertical-control circuit.\n", "2. Symmetrise the machine with `prepare_up_down_symmetric_machine()`—demonstrating how it flags and excludes the odd circuit, recentres the geometry at $Z = 0$, and pairs/averages the remaining coils and boundaries.\n", "3. Quantify the resulting geometric and Green-function changes, verify the even/odd current transforms, and build the final symmetric `tokamak` object for `SymmetryReducedSolver`." ] }, { "cell_type": "markdown", "id": "1", "metadata": {}, "source": [ "### Define an imperfect source machine\n", "\n", "The test machine intentionally includes:\n", "- A central solenoid and independently driven upper/lower shaping and divertor coils.\n", "- Paired passive wall elements.\n", "- A small common vertical offset and centimetre-scale upper/lower mismatches.\n", "- One anti-series vertical-control circuit, which is electrically odd.\n", "\n", "Because `prepare_up_down_symmetric_machine()` operates on deep copies, the original dictionaries are never modified." ] }, { "cell_type": "code", "execution_count": null, "id": "2", "metadata": {}, "outputs": [], "source": [ "from copy import deepcopy\n", "\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "from freegsnke import build_machine, equilibrium_update\n", "from freegsnke.up_down_symmetry import prepare_up_down_symmetric_machine\n", "\n", "plt.rcParams.update({\"figure.dpi\": 120, \"axes.grid\": True})\n", "\n", "\n", "def filament(r, z, *, multiplier=80, polarity=1):\n", " \"\"\"Return one rectangular active-coil filament bundle.\"\"\"\n", " return {\n", " \"R\": [r],\n", " \"Z\": [z],\n", " \"dR\": 0.07,\n", " \"dZ\": 0.07,\n", " \"resistivity\": 1.55e-8,\n", " \"polarity\": polarity,\n", " \"multiplier\": multiplier,\n", " }\n", "\n", "\n", "def rectangle(name, group, r, z, half_width=0.025):\n", " \"\"\"Return one quadrilateral passive element.\"\"\"\n", " return {\n", " \"name\": name,\n", " \"element\": group,\n", " \"R\": np.array(\n", " [r - half_width, r + half_width, r + half_width, r - half_width]\n", " ),\n", " \"Z\": np.array(\n", " [z - half_width, z - half_width, z + half_width, z + half_width]\n", " ),\n", " \"resistivity\": 5.5e-7,\n", " }\n", "\n", "\n", "def build_imperfect_source_machine():\n", " \"\"\"Build an in-memory, approximately symmetric toy tokamak description.\"\"\"\n", " z0 = 0.008 # unknown to the preparation: an 8 mm global source offset\n", " active = {\n", " \"solenoid\": {\n", " **filament(0.24, z0, multiplier=20),\n", " \"R\": [0.24] * 6,\n", " \"Z\": z0 + np.array([-1.05, -0.63, -0.21, 0.21, 0.63, 1.05]),\n", " }\n", " }\n", "\n", " # Independent upper/lower circuits with small source-description errors.\n", " locations = {\n", " \"PF1\": (0.43, 1.18),\n", " \"PF2\": (0.66, 1.34),\n", " \"PF3\": (1.35, 1.20),\n", " \"PF4\": (1.63, 0.87),\n", " \"PF5\": (1.72, 0.48),\n", " \"PF6\": (1.76, 0.17),\n", " }\n", " for index, (name, (r, z)) in enumerate(locations.items()):\n", " dr = (index - 2.5) * 0.012\n", " dz = (-1) ** index * 0.025\n", " active[f\"{name}_upper\"] = filament(r, z0 + z)\n", " active[f\"{name}_lower\"] = filament(r + dr, z0 - z + dz)\n", "\n", " # Opposite winding polarities make this circuit odd under reflection.\n", " active[\"vertical_control\"] = {\n", " \"upper\": filament(1.83, z0 + 0.31),\n", " \"lower\": filament(1.83, z0 - 0.31, polarity=-1),\n", " }\n", "\n", " passive = []\n", " angles = np.linspace(np.pi / 18, 17 * np.pi / 18, 9)\n", " for index, angle in enumerate(angles):\n", " r = 1.02 + 0.63 * np.cos(angle)\n", " z = 1.02 * np.sin(angle)\n", " dr = 0.020 * np.sin(2 * angle)\n", " dz = 0.025 * np.cos(angle)\n", " passive.extend(\n", " [\n", " rectangle(f\"wall_{index}_upper\", f\"wall_{index}\", r, z0 + z),\n", " rectangle(\n", " f\"wall_{index}_lower\",\n", " f\"wall_{index}\",\n", " r + dr,\n", " z0 - z + dz,\n", " ),\n", " ]\n", " )\n", "\n", " theta = np.linspace(0.0, 2 * np.pi, 120, endpoint=True)\n", " r_limiter = 0.98 + 0.4 * np.cos(theta + 0.13 * np.sin(theta)) + 0.03 * np.sin(theta)\n", " z_limiter = z0 + 0.7 * np.sin(theta) + 0.04 * np.cos(theta) ** 2 * np.sin(theta + 0.4)\n", " limiter = [\n", " {\"R\": float(r), \"Z\": float(z)} for r, z in zip(r_limiter, z_limiter)\n", " ]\n", "\n", " r_wall = 0.98 + 0.45 * np.cos(theta + 0.13 * np.sin(theta)) + 0.03 * np.sin(theta)\n", " z_wall = z0 + 0.75 * np.sin(theta) + 0.04 * np.cos(theta) ** 2 * np.sin(theta + 0.4)\n", " wall = [{\"R\": float(r), \"Z\": float(z)} for r, z in zip(r_wall, z_wall)]\n", " return active, passive, limiter, wall\n", "\n", "\n", "def active_parts(circuit):\n", " \"\"\"Yield direct and compound active-coil parts in one form.\"\"\"\n", " if \"R\" in circuit:\n", " return [circuit]\n", " return [\n", " part\n", " for part in circuit.values()\n", " if isinstance(part, dict) and \"R\" in part\n", " ]\n", "\n", "\n", "def centroid(element):\n", " return float(np.mean(element[\"R\"])), float(np.mean(element[\"Z\"]))\n", "\n", "\n", "def plot_description(ax, active, passive, boundary, *, title, z_offset=0.0):\n", " \"\"\"Plot a raw machine description without first building a tokamak object.\"\"\"\n", " for name, circuit in active.items():\n", " colour = \"tab:red\" if name == \"vertical_control\" else \"tab:blue\"\n", " parts = active_parts(circuit)\n", " for part in parts:\n", " r, z = centroid(part)\n", " ax.scatter(r, z + z_offset, s=36, color=colour, zorder=4)\n", " # Label a compound series circuit beside its upper bundle.\n", " r_label, z_label = max((centroid(part) for part in parts), key=lambda p: p[1])\n", " ax.annotate(\n", " name,\n", " (r_label, z_label + z_offset),\n", " fontsize=6,\n", " xytext=(3, 2),\n", " textcoords=\"offset points\",\n", " )\n", "\n", " for element in passive:\n", " r = np.r_[element[\"R\"], element[\"R\"][0]]\n", " z = np.r_[element[\"Z\"], element[\"Z\"][0]] + z_offset\n", " ax.fill(r, z, color=\"0.65\", alpha=0.55, linewidth=0.5, edgecolor=\"0.25\")\n", "\n", " points = np.asarray(\n", " [[item[\"R\"], item[\"Z\"] + z_offset] for item in boundary]\n", " )\n", " ax.plot(*np.vstack((points, points[0])).T, color=\"black\", linewidth=1.2)\n", " ax.axhline(0.0, color=\"0.35\", linewidth=0.8, linestyle=\":\")\n", " ax.set(title=title, xlabel=\"R [m]\", ylabel=\"Z [m]\", aspect=\"equal\")\n", " ax.set_xlim(0.05, 1.95)\n", " ax.set_ylim(-1.5, 1.5)\n", "\n", "\n", "active_source, passive_source, limiter_source, wall_source = (\n", " build_imperfect_source_machine()\n", ")\n", "\n", "source_tokamak = build_machine.tokamak(\n", " active_coils_data=active_source,\n", " passive_coils_data=passive_source,\n", " limiter_data=limiter_source,\n", " wall_data=wall_source,\n", ")" ] }, { "cell_type": "markdown", "id": "3", "metadata": {}, "source": [ "So now we can clearly see that this machine is not up-down symmetric!\n", "\n", "The upper coils, passives, and limiter/wall are a few cms \"off\" vs. their lower counterparts. " ] }, { "cell_type": "code", "execution_count": null, "id": "4", "metadata": {}, "outputs": [], "source": [ "# plot\n", "fig, ax = plt.subplots(figsize=(4, 6))\n", "source_tokamak.plot(axis=ax, show=False)\n", "ax.plot(source_tokamak.limiter.R, source_tokamak.limiter.Z, \"k-\", linewidth=1.2)\n", "ax.plot(source_tokamak.wall.R, source_tokamak.wall.Z, \"r-\", linewidth=1.2)\n", "ax.axhline(0.0, color=\"0.35\", linewidth=0.8, linestyle=\":\")\n", "ax.set( xlabel=\"Major radius, R [m]\", ylabel=\"Height, Z [m]\", aspect=\"equal\")\n", "ax.set_xlim(0.05, 1.95)\n", "ax.set_ylim(-1.5, 1.5)\n", "plt.show()\n" ] }, { "cell_type": "markdown", "id": "5", "metadata": {}, "source": [ "### Symmetrise the machine (detecting and excluding odd circuits)\n", "\n", "Let $G_{\\mathrm{coil}}(R, Z)$ denote the poloidal-flux Green function produced on the grid by a unit current in a given active circuit. By default, `prepare_up_down_symmetric_machine()` raises an error if any active circuit has odd reflection parity ($G_{\\mathrm{coil}}(R, 2Z_0 - Z) = -G_{\\mathrm{coil}}(R, Z)$), preventing a circuit from being dropped silently.\n", "\n", "After verifying that the expected error is raised, we pass `exclude_odd_active=True` to explicitly exclude the odd circuit, shift all retained geometry by $-Z_0$ so the midplane lies at $Z = 0$, average the reflected pairs, and return the `PreparedUpDownMachine` object." ] }, { "cell_type": "code", "execution_count": null, "id": "6", "metadata": {}, "outputs": [], "source": [ "# this call shows which circuits cannot be included in the new up-down symmetric model\n", "try:\n", " prepare_up_down_symmetric_machine(\n", " active_source,\n", " passive_source,\n", " limiter_data=limiter_source,\n", " wall_data=wall_source,\n", " z_midplane=\"auto\",\n", " )\n", "except ValueError as error:\n", " print(\"Safety check stopped preparation:\")\n", " print(\" \", error)" ] }, { "cell_type": "code", "execution_count": null, "id": "7", "metadata": {}, "outputs": [], "source": [ "# this call will remove the named circuit above and symmetrise the machine\n", "symmetric_machine_data = prepare_up_down_symmetric_machine(\n", " active_source,\n", " passive_source,\n", " limiter_data=limiter_source,\n", " wall_data=wall_source,\n", " z_midplane=\"auto\",\n", " exclude_odd_active=True,\n", ")" ] }, { "cell_type": "markdown", "id": "8", "metadata": {}, "source": [ "Let's view the changes that have been made!" ] }, { "cell_type": "code", "execution_count": null, "id": "9", "metadata": {}, "outputs": [], "source": [ "# plots the difference between the old and new machine\n", "symmetric_machine_data.plot()" ] }, { "cell_type": "markdown", "id": "10", "metadata": {}, "source": [ "The next plot shows which coils and passives were linked together during the symmetrisation. " ] }, { "cell_type": "code", "execution_count": null, "id": "11", "metadata": {}, "outputs": [], "source": [ "# Show the inferred pairings on the symmetrised machine description. The\n", "# connecting lines are diagnostic only; they are not conductor geometry.\n", "fig, ax = plt.subplots(figsize=(4,6))\n", "plot_description(\n", " ax,\n", " symmetric_machine_data.active_coils_data,\n", " symmetric_machine_data.passive_coils_data,\n", " symmetric_machine_data.limiter_data,\n", " title=\"Linked coils and passives\",\n", ")\n", "\n", "for pair in symmetric_machine_data.active_pairs:\n", " ru, zu = centroid(symmetric_machine_data.active_coils_data[pair.upper_name])\n", " rl, zl = centroid(symmetric_machine_data.active_coils_data[pair.lower_name])\n", " ax.plot([ru, rl], [zu, zl], color=\"tab:blue\", alpha=0.35, linewidth=0.8)\n", "\n", "passive_lookup = {item[\"name\"]: item for item in symmetric_machine_data.passive_coils_data}\n", "for pair in symmetric_machine_data.passive_pairs:\n", " ru, zu = centroid(passive_lookup[pair.upper_name])\n", " rl, zl = centroid(passive_lookup[pair.lower_name])\n", " ax.plot([ru, rl], [zu, zl], color=\"tab:orange\", alpha=0.35, linewidth=0.6)\n", "\n", "plt.show()\n" ] }, { "cell_type": "markdown", "id": "12", "metadata": {}, "source": [ "### Inspect geometric discrepancies\n", "\n", "For each conductor pair with $N$ discretisation (or polygon) points $\\mathbf{x}_{u,k}$ and $\\mathbf{x}_{l,k}$ ($k = 1, \\dots, N$), the reported mismatch is the RMS Euclidean distance between the upper points and the reflected lower points before averaging:\n", "\n", "$$\n", "d_{\\mathrm{RMS}} = \\sqrt{\\frac{1}{N} \\sum_{k=1}^{N} \\left\\lVert \\mathbf{x}_{u,k} - \\mathcal{R}_Z \\mathbf{x}_{l,k} \\right\\rVert^2}.\n", "$$\n", "\n", "For the limiter and wall, the symmetric footprint is the intersection of the outline with its reflection; whenever the footprint changes, a warning is emitted." ] }, { "cell_type": "code", "execution_count": null, "id": "13", "metadata": {}, "outputs": [], "source": [ "# check the biggest changes\n", "largest = symmetric_machine_data.largest_geometry_discrepancies(count=10)\n", "print(\"Largest pre-symmetrisation geometry discrepancies\")\n", "for record in largest:\n", " print(\n", " f\"{record.component:8s} {record.upper_name:18s} / \"\n", " f\"{record.lower_name:18s}: {1e3 * record.reflected_rms:6.3f} mm\"\n", " )\n", "\n", "#\n", "GEOMETRY_ACCEPTANCE = 0.050 # 50 mm RMS point distance\n", "symmetric_machine_data.check_geometry_tolerance(GEOMETRY_ACCEPTANCE)\n", "\n", "\n", "# lets plot them side by side\n", "fig, axes = plt.subplots(1, 2, figsize=(8, 6), sharex=True, sharey=True)\n", "plot_description(\n", " axes[0],\n", " active_source,\n", " passive_source,\n", " limiter_source,\n", " title=\"Source geometry\",\n", ")\n", "plot_description(\n", " axes[1],\n", " symmetric_machine_data.active_coils_data,\n", " symmetric_machine_data.passive_coils_data,\n", " symmetric_machine_data.limiter_data,\n", " title=\"Exactly symmetric geometry\",\n", ")\n", "plt.tight_layout()\n", "plt.show()\n" ] }, { "cell_type": "markdown", "id": "14", "metadata": {}, "source": [ "### Compare magnetic (Green-function) changes\n", "\n", "We can compare the changes in Green's function for the coils/passives in order to see how different things will be in the new machine. \n", "\n", "Let $G_{\\mathrm{source}}$ and $G_{\\mathrm{sym}}$ denote the sampled Green-function matrices mapping unit conductor currents to poloidal flux on the equilibrium grid before and after symmetrisation, respectively. Using the Frobenius norm $\\lVert \\cdot \\rVert_F$, we report the relative percentage change separately for active and passive conductors:\n", "\n", "$$\n", "\\epsilon_G = 100\\,\\frac{\\lVert G_{\\mathrm{sym}} - G_{\\mathrm{source}} \\rVert_F}{\\lVert G_{\\mathrm{source}} \\rVert_F}.\n", "$$\n", "\n", "A small value of $\\epsilon_G$ indicates that symmetrisation closely preserves the magnetic response of the original machine." ] }, { "cell_type": "code", "execution_count": null, "id": "15", "metadata": {}, "outputs": [], "source": [ "# Exclude the odd circuit from the source comparison so both bases have\n", "# identical labels, ordering, and dimensions. The comparison then isolates\n", "# recentering and geometric averaging, rather than circuit removal.\n", "retained_source_active = {\n", " name: deepcopy(active_source[name]) for name in symmetric_machine_data.original_active_names\n", "}\n", "\n", "raw_tokamak = build_machine.tokamak(\n", " active_coils_data=retained_source_active,\n", " passive_coils_data=passive_source,\n", " limiter_data=limiter_source,\n", " wall_data=wall_source,\n", ")\n", "\n", "symmetric_tokamak = build_machine.tokamak(\n", " active_coils_data=symmetric_machine_data.active_coils_data,\n", " passive_coils_data=symmetric_machine_data.passive_coils_data,\n", " limiter_data=symmetric_machine_data.limiter_data,\n", " wall_data=symmetric_machine_data.wall_data,\n", ")\n", "\n", "eq_kwargs = dict(\n", " Rmin=0.05,\n", " Rmax=1.95,\n", " Zmin=-1.5,\n", " Zmax=1.5,\n", " nx=65,\n", " ny=65,\n", " psi=None,\n", ")\n", "\n", "# Equilibrium supplies a common grid and the sampled conductor Green basis;\n", "# this audit does not require a Grad-Shafranov equilibrium solve.\n", "raw_eq = equilibrium_update.Equilibrium(tokamak=raw_tokamak, **eq_kwargs)\n", "symmetric_eq = equilibrium_update.Equilibrium(tokamak=symmetric_tokamak, **eq_kwargs)\n", "\n", "# _vgreen is the internal conductor-to-grid poloidal-flux basis. Active rows\n", "# precede passive rows; use the retained\n", "# active count to split both machines at the same coordinate boundary.\n", "n_active = len(symmetric_machine_data.original_active_names)\n", "raw_active_g = raw_eq._vgreen[:n_active]\n", "sym_active_g = symmetric_eq._vgreen[:n_active]\n", "raw_passive_g = raw_eq._vgreen[n_active:]\n", "sym_passive_g = symmetric_eq._vgreen[n_active:]\n", "\n", "\n", "def percentage_change(original, updated):\n", " return 100 * np.linalg.norm(updated - original) / np.linalg.norm(original)\n", "\n", "\n", "active_change = percentage_change(raw_active_g, sym_active_g)\n", "passive_change = percentage_change(raw_passive_g, sym_passive_g)\n", "print(f\"Active Green-basis change: {active_change:.4f}%\")\n", "print(f\"Passive Green-basis change: {passive_change:.4f}%\")\n", "\n", "# The scalar percentages summarize the whole basis. Summing squared source\n", "# rows gives a current-coordinate-independent basis magnitude at each grid\n", "# point. Errors are normalized by its global maximum to avoid unstable local\n", "# ratios where the source field basis is nearly zero.\n", "active_strength = np.sqrt(np.sum(raw_active_g**2, axis=0))\n", "passive_strength = np.sqrt(np.sum(raw_passive_g**2, axis=0))\n", "active_error = np.sqrt(np.sum((sym_active_g - raw_active_g) ** 2, axis=0))\n", "passive_error = np.sqrt(np.sum((sym_passive_g - raw_passive_g) ** 2, axis=0))\n", "extent = [raw_eq.Rmin, raw_eq.Rmax, raw_eq.Zmin, raw_eq.Zmax]" ] }, { "cell_type": "code", "execution_count": null, "id": "16", "metadata": {}, "outputs": [], "source": [ "# plot the differences\n", "fig, axes = plt.subplots(2, 2, figsize=(8, 10), sharex=True, sharey=True)\n", "maps = [\n", " (active_strength, \"source active basis magnitude\"),\n", " (100 * active_error / np.max(active_strength), \"active change / max source [%]\"),\n", " (passive_strength, \"source passive basis magnitude\"),\n", " (\n", " 100 * passive_error / np.max(passive_strength),\n", " \"passive change / max source [%]\",\n", " ),\n", "]\n", "for ax, (field, title) in zip(axes.flat, maps):\n", " image = ax.imshow(field.T, origin=\"lower\", extent=extent, aspect=\"auto\")\n", " ax.set_title(title)\n", " ax.set_xlabel(\"R [m]\")\n", " ax.set_ylabel(\"Z [m]\")\n", " fig.colorbar(image, ax=ax, shrink=0.82)\n", "plt.tight_layout()\n", "plt.show()\n", "\n" ] }, { "cell_type": "markdown", "id": "17", "metadata": {}, "source": [ "### Transform currents between original and reduced bases\n", "\n", "`PreparedUpDownMachine` exposes the linear maps between the original active-current vector $\\mathbf{I}$ and the reduced even and odd current vectors $\\mathbf{I}_+$ and $\\mathbf{I}_-$:\n", "\n", "$$\n", "\\mathbf{I}_+ = T_+ \\mathbf{I}, \\qquad \\mathbf{I}_- = T_- \\mathbf{I}, \\qquad \\mathbf{I} = U_+ \\mathbf{I}_+ + U_- \\mathbf{I}_-,\n", "$$\n", "\n", "where $T_+$ (`active_original_to_even`) and $T_-$ (`active_original_to_odd`) project onto the even and odd bases, and $U_+$ (`active_even_to_original`) and $U_-$ (`active_odd_to_original`) map back to the original circuit basis. Here we verify that `split_active_currents()` and `combine_active_currents()` invert one another to machine precision." ] }, { "cell_type": "code", "execution_count": null, "id": "18", "metadata": {}, "outputs": [], "source": [ "# A synthetic reconstructed current vector in the documented retained order.\n", "# The excluded vertical_control circuit is intentionally not part of this\n", "# transform because strict even evolution has no coordinate for it.\n", "original_currents = np.array(\n", " [7_000.0]\n", " + [\n", " value\n", " for pair in [\n", " (2_100, 1_900),\n", " (-3_200, -2_800),\n", " (4_200, 3_900),\n", " (-2_500, -2_650),\n", " (3_100, 2_850),\n", " (-1_700, -1_450),\n", " ]\n", " for value in pair\n", " ]\n", ")\n", "assert len(original_currents) == len(symmetric_machine_data.original_active_names)\n", "\n", "# Pair averages are the currents retained by strict even evolution; pair\n", "# differences quantify the odd content discarded by that projection.\n", "even_currents, odd_currents = symmetric_machine_data.split_active_currents(original_currents)\n", "# Keeping both coordinates must reconstruct the source exactly. Omitting\n", "# odd_currents deliberately returns the closest exactly even vector.\n", "reconstructed = symmetric_machine_data.combine_active_currents(even_currents, odd_currents)\n", "even_projection = symmetric_machine_data.combine_active_currents(even_currents)\n", "np.testing.assert_allclose(reconstructed, original_currents)\n", "\n", "print(\"Original active order:\", symmetric_machine_data.original_active_names)\n", "print(\"Reduced even order: \", symmetric_machine_data.even_active_names)\n", "print(\"Odd pair coordinates: \", symmetric_machine_data.active_odd_names)\n", "print(\n", " f\"Reconstruction error: \"\n", " f\"{np.linalg.norm(reconstructed - original_currents):.3e} A\"\n", ")\n", "\n", "# plot differences\n", "x = np.arange(len(original_currents))\n", "width = 0.38\n", "fig, axes = plt.subplots(2, 1, figsize=(8, 6), constrained_layout=True)\n", "axes[0].bar(x - width / 2, original_currents, width, label=\"original\")\n", "axes[0].bar(x + width / 2, even_projection, width, label=\"even projection\")\n", "axes[0].set_xticks(x, symmetric_machine_data.original_active_names, rotation=55, ha=\"right\")\n", "axes[0].set_ylabel(\"current [A]\")\n", "axes[0].set_title(\"Original currents and their exactly even projection\")\n", "axes[0].legend()\n", "\n", "odd_x = np.arange(len(odd_currents))\n", "axes[1].bar(odd_x, odd_currents, color=\"tab:orange\")\n", "axes[1].set_xticks(odd_x, symmetric_machine_data.active_odd_names, rotation=35, ha=\"right\")\n", "axes[1].set_ylabel(\"odd current coordinate [A]\")\n", "axes[1].set_title(\"Discarded upper/lower current differences\")\n", "plt.show()\n" ] }, { "cell_type": "markdown", "id": "19", "metadata": {}, "source": [ "### Summary \n", "\n", "In summary, the new `prepare_up_down_symmetric_machine()`:\n", "- Fits and removes a common vertical offset when `z_midplane=\"auto\"`.\n", "- Identifies reflected active and passive element pairs and records pre-averaging geometric mismatches.\n", "- Averages paired geometry onto exact reflection symmetry and intersects the limiter and wall with their reflections.\n", "- Detects and explicitly records electrically odd active circuits.\n", "- Provides linear transforms between original and even/odd active-current coordinates, together with the passive reflection operator $S_p$ needed for reduced dynamics.\n", "\n", "Deciding whether the resulting Green-function and geometric changes are physically acceptable remains a modelling choice for the user. Furthermore, excluded odd active circuits are not modelled in the strictly even solver.\n", "\n", "Let's take a look at the final up-down symmetric machine and some summary statistics." ] }, { "cell_type": "code", "execution_count": null, "id": "20", "metadata": {}, "outputs": [], "source": [ "# Passive elements remain separate in the machine description. Their\n", "# reflection operator lets the evolutive solver select even passive modes.\n", "passive_reflection = symmetric_machine_data.passive_reflection_operator\n", "np.testing.assert_allclose(passive_reflection, passive_reflection.T)\n", "np.testing.assert_allclose(\n", " passive_reflection @ passive_reflection,\n", " np.eye(len(passive_reflection)),\n", ")\n", "\n", "\n", "# (I + S_p) / 2 projects passive currents onto the even subspace. The trace\n", "# of a projector is its rank, hence the number of retained passive modes.\n", "n_passive_even = int(\n", " np.trace((np.eye(len(passive_reflection)) + passive_reflection) / 2)\n", ")\n", "print(\"Final active series circuits:\", symmetric_machine_data.even_active_names)\n", "print(\"Final passive elements: \", len(symmetric_machine_data.passive_names))\n", "print(\"Passive even coordinates: \", n_passive_even)\n", "print(\"Odd source circuits omitted: \", symmetric_machine_data.excluded_odd_active_names)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "21", "metadata": {}, "outputs": [], "source": [ "# final machine\n", "fig, ax = plt.subplots(figsize=(4, 6))\n", "symmetric_tokamak.plot(axis=ax, show=False)\n", "ax.plot(symmetric_tokamak.limiter.R, symmetric_tokamak.limiter.Z, \"k-\", linewidth=1.2)\n", "ax.plot(symmetric_tokamak.wall.R, symmetric_tokamak.wall.Z, \"r-\", linewidth=1.2)\n", "ax.axhline(0.0, color=\"0.35\", linewidth=0.8, linestyle=\":\")\n", "ax.set( xlabel=\"Major radius, R [m]\", ylabel=\"Height, Z [m]\", aspect=\"equal\")\n", "ax.set_xlim(0.05, 1.95)\n", "ax.set_ylim(-1.5, 1.5)\n", "plt.show()\n" ] }, { "cell_type": "code", "execution_count": null, "id": "22", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "23", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "24", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "25", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "26", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "freegsnke", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.20" } }, "nbformat": 4, "nbformat_minor": 5 }